#! /usr/bin/env python
# -*- coding:utf-8 -*-

import requests
from lxml import etree
import datetime
import re
import uuid
import sys
import json
import logging
import demjson

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 西安工程大学教务处IP
school_base_url = "http://202.200.206.54/"
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
}
session = requests.Session()
resp = {
    'error' : 0,
    'msg' : 'success',
    'data' : {},
}
params = ['user_name', 'user_gender', 'user_birthday', 'user_college', 'user_class']

def getUserInfo(req_data):

    req_data = demjson.decode(req_data)
    #print(req_data)
    data = {
        '__VIEWSTATE': 'dDw0NTM2NjI5MTg7Oz5khnyP8uikO2NTOQNIZOHZCUyxvA==',  # 固定
        'txtUserName': req_data['student_id'],  # 学号
        'Textbox1': '',
        'TextBox2': req_data['password'],  # 密码
        'txtSecretCode': req_data['code'],  # 验证码
        'RadioButtonList1': '(unable to decode value)',  # 固定
        'Button1': '',
        'lbLanguage': '',
        'hidPdrs': '',
        'hidsc': '',
    }

    # 登录必须带的头
    new_headers = {
        'Referer': 'http:/' + req_data['location_url'],
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
    }
    # 必须请求登录一下
    response = session.post(url=req_data['have_location_url'], headers=new_headers, data=data)
    if len(response.history) == 0:
        resp['msg'] = '登陆失败，请检查登陆信息'
        resp['error'] = '1'
        return resp
    student_id = req_data['student_id']
    html = etree.HTML(response.text)
    name = html.xpath('.//span[(@id="xhxm")]')[0].text
    location_word = req_data["location_url"].split('/')[1]
    # 学号
    id = int(student_id)
    # 请求课程表地址(固定)
    user_info_url = 'http://202.200.206.54/' + location_word + '/xsgrxx.aspx?xh=' + str(id) + '&xm=%CE%E2%E9%AA&gnmkdm=N121501'
    # 请求课程表必须带的头
    headers = {
        'Referer': 'http://202.200.206.54/' + location_word + '/xs_main.aspx?xh=' + str(id),
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
    }
    user_info = session.get(headers=headers, url=user_info_url).text
    tree = etree.HTML(user_info)

    user_name = tree.xpath('//*[@id="xm"]/text()')[0]
    user_gender = tree.xpath('//*[@id="XB"]/option[@selected="selected"]/@value')[0]
    user_birthday = tree.xpath('//*[@id="csrq"]/@value')[0]
    user_college = tree.xpath('//*[@id="xy"]/@value')[0]
    user_class = tree.xpath('//*[@id="xzb"]/@value')[0]

    for param in params:
        if eval(param):
            resp['data'][param] = eval(param)
    return json.dumps(resp)

def main():
    req_data = sys.argv[1]
    #print(req_data)
    resp = getUserInfo(req_data)
    print(resp)
    return resp

if __name__ == '__main__':
    main()
